<template>
	<div ref="refUnityMap" :class="$style['unity-map-container']" id="unityPlayer"></div>
	<DialogDahuaPlayer ref="refDialogDahuaPlayer" />
</template>

<script setup name="unityMap">
import { ref, nextTick, onMounted, onBeforeUnmount } from 'vue'
import VueTypes from 'vue-types'
import useEventBus from "@/utils/event.bus"
import { ElMessage } from 'element-plus'
import { loadScript } from "@/utils"
import {
	fetchMapMarkersU3D, fetchMapSeeVideoU3D
} from '@/api/map.services'
import { fetchEventsSimulate } from '@/api/event.services'
const props = defineProps({
	mapInfo: VueTypes.shape({
		map_file: String,
	}).loose.def({})
})

let eventBus = useEventBus(true)
let unity3d = null

const refUnityMap = ref(null)
const markers = ref([])
import DialogDahuaPlayer from '@/components/DialogDahuaPlayer.vue'
const refDialogDahuaPlayer = ref(null)
const initUnityMap = async () => {
	// console.log('🚀[ ][ initUnityMap ][ props.mapInfo ] =>', props.mapInfo)
	await nextTick()

	const path = props.mapInfo.map_file.replace(/\/$/, '')

	// unity3D Map 所用的 webgl 文件是跟着项目走的，所以每次都需要动态的加载它生成的加载文件
	const loaded = Promise.all([
		loadScript(`${path}/TemplateData/UnityProgress.js`, 'UnityProgress'), // 加载进度条
		loadScript(`${path}/Build/UnityLoader.js`, 'UnityLoader') // 加载 unity3D 的 webgl 文件
	])

	try {
		await loaded

		unity3d = UnityLoader.instantiate(
			'unityPlayer',
			`${path}/Build/unity.map.json`,
			{ onProgress: UnityProgress }
		)
	} catch (error) {
		console.error('🚀[ ][ initUnity ][ error ] =>', error)
	}

	// unityMap 触发的报警，地图加载后可以通过这个函数添加报警
	window.raiseFakedAlarm = (moID, alarmSource, alarmID) => {
		console.log('U3D模拟触发', moID)
		console.log('U3D模拟触发', alarmSource)
		console.log('U3D模拟触发', alarmID)
		eventSimulate({ obj_id: moID, meters: alarmSource })
		addALarmRaiseU3D(moID, alarmSource, alarmID)
		// console.log('🚀[ ][ initUnityMap ][ moID, alarmSource, alarmID ] =>', moID, alarmSource, alarmID)
		// toDo 这里需要获取防区的对应数据

	}

	// unityMap 触发的 清除报警，地图加载后可以通过这个函数清除地图的报警
	window.clearAlarm = (alarmID) => {
		// console.log('🚀[ ][ initUnityMap ][ alarmID ] =>', alarmID)
		// 里面的属性必须存在，值除了 AlarmID Cleared 之外都是假的，只是 untiyMap 的内置函数必须有这些字段
		const parm = `{"RaisedTime":"00:00:00","MeasObjID":"1","MeasObjName":"1","AlarmSource":"1","AlarmSeverity":4,"AlarmID":"${alarmID}","Cleared":true}`

		// 通知 unityMap 清除报警
		unity3d?.SendMessage('MainUI', 'RemoveAlarm', parm)
	}

	// unityMap 触发的 布防,moIDs防区编号
	window.enableMeasObj = (moIDs) => {
		// toDo 这里需要调用布防的接口
	}

	// unityMap 触发的 撤防,moIDs防区编号
	window.disableMeasObj = (moIDs) => {
		// toDo 这里需要调用撤防的接口
	}
	window.openLiveVideoByIDChannel = async (obj) => {
		const result = await fetchMapSeeVideoU3D({ obj_id: obj })
		if (result.code == 1) {
			if (result.data.length == 0) {
				ElMessage.warning('暂未关联视频')
				return
			}
			const playerData = {
				type: 'real', // [real: 实时预览, record: 录像回放],
				channels: result.data.map(item => {
					return {
						channelCode: item.camera_uniq_code,
						channelName: item.camera_name
					}
				}),
				title: null
			}
			refDialogDahuaPlayer.value.open(playerData, result.data)
		}
	}
}

const eventSimulate = async (params) => {
	console.log('🚀[ ]开始请求模拟接口')
	await fetchEventsSimulate(params)
}
const getMapMarker = async () => {
	const result = await fetchMapMarkersU3D(props.mapInfo.id)

	if (result.code == 1) {
		markers.value = result.data.data.filter(item => !!item.obj_id)
		console.log('🚀[ ][ getMapMarker ][ markers.value ] =>', markers.value)
	}
}

const handleAddAlarm = (event) => {
	console.log('收到报警事件,开始U3D弹框', event)
	const simulate = event.is_simulate || 1
	if (simulate == 2) return//模拟报警返回
	console.log('🚀[ ][ handleAddAlarm ][ event ] =>', event)
	const postion = event.meters
	const moid = markers.value.find(item => item.device_id == event.device_id)?.obj_id

	if (!moid) {
		return
	}
	addALarmRaiseU3D(moid, postion, event.alarm_id)
	// window.raiseFakedAlarm?.(moid, postion, event.alarm_id)
}

const addALarmRaiseU3D = (moID, alarmSource, alarmID) => {
	const date = new Date()
	// const year = date.getFullYear()
	// const month = date.getMonth() + 1
	// const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()
	const now_time = hour + ':' + minute + ':' + second
	const area_name = '防区1'
	const parm = `{"RaisedTime":"${now_time}","MeasObjID":"${moID}","MeasObjName":"${area_name}","AlarmSource":"${alarmSource}","AlarmSeverity":4,"AlarmID":${alarmID || 0},"Cleared":false}`

	// 通知 unityMap 添加报警
	unity3d?.SendMessage('MainUI', 'AddAlarm', parm)
}
const handleRemoveAlarm = (event) => {
	//console.log('🚀[ ][ handleRemoveAlarm ][ event ] =>', event)
	window.clearAlarm?.(event.alarm_id)
}
onMounted(() => {
	getMapMarker()
	initUnityMap()

	eventBus.register("eventReal", handleAddAlarm)
	eventBus.register("eventRealUpdate", handleAddAlarm)
	eventBus.register("guardAlarm", handleAddAlarm)
	eventBus.register("eventHandle", handleRemoveAlarm)
})

onBeforeUnmount(() => {
	eventBus.destroy()
	eventBus = null
	unity3d = null
})

</script>
<style lang="scss" module>
.unity-map-container {
	width: 100%;
	height: 100%;
}
</style>